/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.dyn.service;

import com.jeeplus.cms.common.CmsConstant;
import com.jeeplus.cms.util.CmsCacheUtils;
import com.jeeplus.cms.util.CmsUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.cms.column.entity.CmsColumn;
import com.jeeplus.modules.cms.column.service.CmsColumnService;
import com.jeeplus.modules.cms.dm.entity.CmsDynamic;
import com.jeeplus.modules.cms.dm.service.CmsDynamicService;
import com.jeeplus.modules.cms.dyn.entity.CmsContentsDyn;
import com.jeeplus.modules.cms.dyn.mapper.CmsContentsDynMapper;
import com.jeeplus.modules.cms.model.entity.CmsModel;
import com.jeeplus.modules.cms.site.entity.CmsSite;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 动态内容Service
 *
 * @author Sawyer
 * @version 2020-11-26
 */
@Service
@Transactional(readOnly = true)
public class CmsContentsDynService extends CrudService<CmsContentsDynMapper, CmsContentsDyn> {

    @Autowired
    private CmsColumnService columnService;

    @Autowired
    private CmsDynamicService dynamicService;

    @Override
    public CmsContentsDyn get(String id) {
        return super.get(id);
    }

    @Override
    public List<CmsContentsDyn> findList(CmsContentsDyn cmsContentsDyn) {
        return super.findList(cmsContentsDyn);
    }

    @Override
    public List<CmsContentsDyn> findAllList(CmsContentsDyn entity) {
        return findList(entity);
    }

    @Override
    public Page<CmsContentsDyn> findPage(Page<CmsContentsDyn> page, CmsContentsDyn cmsContentsDyn) {
        return super.findPage(page, cmsContentsDyn);
    }

    @Override
    @Transactional(readOnly = false)
    public void save(CmsContentsDyn cmsContentsDyn) {
        // 设置siteId
        String siteId = "";
        if (null != cmsContentsDyn.getColumn()) {
            CmsColumn cmsColumn = CmsUtils.getColumnById(cmsContentsDyn.getColumn().getId());
            siteId = null != cmsColumn ? cmsColumn.getSiteId() : null;
            cmsContentsDyn.setSiteId(siteId);
        }
        // 新增记录时初始化数据
        if (StringUtils.isBlank(cmsContentsDyn.getId())) {
            cmsContentsDyn.init();
        }
        super.save(cmsContentsDyn);

        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.CONTENT_DYN_LIST_CACHE, siteId);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(CmsContentsDyn cmsContentsDyn) {
        String siteId = get(cmsContentsDyn.getId()).getSiteId();
        super.delete(cmsContentsDyn);
        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.CONTENT_DYN_LIST_CACHE, siteId);
    }

    @Transactional(readOnly = false)
    public void updateHitsAddOne(String id) {
        mapper.updateHitsAddOne(id);

        for (CmsSite site : CmsCacheUtils.getSiteListByCache()) {
            Optional<CmsContentsDyn> optional = CmsCacheUtils.getContentDynListByCache(site.getId(), false)
                    .stream()
                    .filter(item -> id.equals(item.getId()))
                    .findFirst();

            if (optional.isPresent()) {
                optional.get().setHits(null == optional.get().getHits() ? 1 : optional.get().getHits() + 1);
                break;
            }
        }
    }

    /**
     * 前端有请求时定期更新过期置顶权重
     */
    @Transactional(readOnly = false)
    public void updateExpiredWeightToReq() {
        //更新过期权重，间隔1小时
        Date updateExpiredWeightTime = (Date) CmsCacheUtils.getCache(CmsUtils.UPDATE_EXPIRED_WEIGHT_TIME_TO_DYN_CACHE);
        if (updateExpiredWeightTime == null || (updateExpiredWeightTime.getTime() < System.currentTimeMillis())) {
            updateExpiredWeight();
            CmsCacheUtils.putCache(CmsUtils.UPDATE_EXPIRED_WEIGHT_TIME_TO_DYN_CACHE, DateUtils.addHours(new Date(), 1));
        }
    }

    /**
     * 更新过期置顶权重
     */
    @Transactional(readOnly = false)
    public void updateExpiredWeight() {
        mapper.updateExpiredWeight(new CmsContentsDyn());
    }


    /**
     * 获取动态表单模型
     */
    @Transactional(readOnly = false)
    public CmsDynamic getDynamic(CmsContentsDyn contentsDyn) {
        if (null == contentsDyn || null == contentsDyn.getColumn() || StringUtils.isBlank(contentsDyn.getColumn().getId())) {
            return new CmsDynamic();
        }

        // 获取模型英文名
        CmsColumn cmsColumn = CmsUtils.getColumnById(contentsDyn.getColumn().getId());
        if (null == cmsColumn || null == cmsColumn.getModel()) {
            return new CmsDynamic();
        }

        // 获取页面模型
        CmsModel cmsModel = CmsUtils.getModelById(cmsColumn.getModel().getId());
        if (null == cmsModel) {
            return new CmsDynamic();
        }

        final String modelEnName = cmsModel.getEnname();

        // 使用栏目模型的英文名当做动态表单的英文名查找动态表单
        List<CmsDynamic> dynamicList = CmsCacheUtils.getDynamicListByCache(cmsColumn.getSiteId());
        Optional<CmsDynamic> optional = dynamicList.stream()
                .filter(item -> CmsConstant.YES.equals(item.getLockFlag()) && "2".equals(item.getType()) && modelEnName.equals(item.getEnname()))
                .findFirst();
        return optional.orElseGet(CmsDynamic::new);
    }

    public Integer getTotalHitsBySiteId(String siteId) {
        return mapper.getTotalHitsBySiteId(siteId);
    }
}
